<?php

namespace app\common\logic;

use app\common\configs\SettingConf;
use app\common\model\commonModel;
use app\common\model\trCar;
use app\common\model\trDriver;
use app\common\model\trSystemSet;
use app\common\util\Tools;

/**
 * Class Sms
 * 短信逻辑类
 * @package Admin\Controller
 */
class SmsLogic
{
    // 订单支付成功提醒通知分配
    public static function orderRemind($mobile, $mobilePrefix = "86"){
        $remindTpl = trSystemSet::getValue("smsOrderRemindTpl"); // 订单支付成功通知分配单
        if (!empty($remindTpl["remindTpl"]) && $remindTpl["remindTplStatus"] == "1") { // 可以发短信了
            if(self::sendSms($remindTpl["remindTpl"], [], $mobile, $mobilePrefix)){
                self::recordLog($remindTpl["remindTpl"], $mobile, "订单支付成功提醒通知分配");
            }
        }
        return true;
    }

    // 提醒订单支付成功
    public static function orderPay($data){
        $payTpl = trSystemSet::getValue("smsPayTpl");
        if(!empty($payTpl["payTpl"]) && $payTpl["payTplStatus"] == "1" && !empty($data)){ // 可以发短信了
            $tel = trSystemSet::getValue("customerServiceConfig");
            if (empty($tel)) {
                $tel["territoryTel"] = "";  //境内电话
                $tel["abroadTel"] = ""; //境外电话
            }
            if(self::sendSms($payTpl["payTpl"], [
                "：".$data["orderSn"], "：".$data["payMoney"], "：".$data["typeName"], "：".$data["reserveTime"],
                "：".$data["addressFrom"], "：".$data["rideNumber"], $tel["territoryTel"], $tel["abroadTel"]
            ], $data["mobile"], $data["mobilePrefix"])){
                self::recordLog($payTpl["payTpl"], $data["mobile"], "提醒订单支付成功");
            }
        }
        return true;
    }

    // 取消订单通知
    public static function orderCancel($orderSn, $data){
        $cancelTpl = trSystemSet::getValue("smsCancelTpl");
        if(!empty($cancelTpl["cancelTpl"]) && $cancelTpl["cancelTplStatus"] == "1"){ // 可以发短信了
            if(empty($data)){
                return true;
            }
            $tel = trSystemSet::getValue("customerServiceConfig");
            if (empty($tel)) {
                $tel["territoryTel"] = "";  //境内电话
                $tel["abroadTel"] = ""; //境外电话
            }
            if(self::sendSms($cancelTpl["cancelTpl"], [
                "：".$orderSn,"：".$data["reason"], $tel["territoryTel"], $tel["abroadTel"]
            ], $data["mobile"], $data["mobilePrefix"])){
                self::recordLog($cancelTpl["cancelTpl"], $data["mobile"], "取消订单通知");
            }
        }
        return true;
    }

    // 通知用户订单已分配
    public static function orderAllocate($data){
        $allocateTpl = trSystemSet::getValue("smsAllocateTpl"); //订单分配成功
        if(!empty($allocateTpl["allocateTpl"]) && $allocateTpl["allocateTplStatus"] == "1"){ // 可以发短信了
            if(!empty($data)) {
                $carModel = new trCar();
                $carData = $carModel->getFields("plate_number,car_type,appearance", ["id" => $data["allotCarId"]]);
                $tel = trSystemSet::getValue("customerServiceConfig");
                if (empty($tel)) {
                    $tel["territoryTel"] = "";  //境内电话
                    $tel["abroadTel"] = ""; //境外电话
                }
                $data["mobilePrefix"] = substr($data["mobile"], 0, -11);
                $data["mobile"] = substr($data["mobile"], -11);
                $driverModel = new trDriver();
                $driverMobile = $driverModel->getValue("mobile", ["id" => $data["allotDriverId"]]);
                if(self::sendSms($allocateTpl["allocateTpl"], [
                    "：" . $data["orderSn"], "：" . $data["addressFrom"], "：" . $carData["carTypeText"] . "（外形：{$carData["appearance"]}）", "：" . $carData["plateNumber"],
                    "：" . $driverMobile, "：" . $data["reserveTime"], "：" . $data["rideNumber"], "：" . $data["typeName"], $tel["territoryTel"], $tel["abroadTel"]
                ], $data["mobile"], $data["mobilePrefix"])){
                    self::recordLog($allocateTpl["allocateTpl"], $data["mobile"], "通知用户订单已分配");
                }
            }
        }
        return true;
    }

    // 通知司机订单已分配
    public static function orderAccept($data){
        $acceptTpl = trSystemSet::getValue("smsAcceptTpl"); // 司机接收订单 -- 司机端
        if(!empty($acceptTpl["acceptTpl"]) && $acceptTpl["acceptTplStatus"] == "1"){ // 可以发短信了
            if(!empty($data)) {
                $tel = trSystemSet::getValue("customerServiceConfig");
                if (empty($tel)) {
                    $tel["territoryTel"] = "";  //境内电话
                    $tel["abroadTel"] = ""; //境外电话
                }
                $driverModel = new trDriver();
                $driverData = $driverModel->getFields("mobile,prefix", ["id" => $data["allotDriverId"]], true, false);
                if(self::sendSms($acceptTpl["acceptTpl"], [
                    "：" . $data["orderSn"], "：" . $data["payMoney"], "：" . $data["typeName"],
                    "：" . $data["reserveTime"], "：" . $data["addressFrom"], "：" . $data["rideNumber"], $tel["territoryTel"], $tel["abroadTel"]
                ], $driverData["mobile"], $driverData["prefix"])){
                    self::recordLog($acceptTpl["acceptTpl"], $driverData["mobile"], "通知司机订单已分配");
                }
            }
        }
        return true;
    }

    // 订单退款通知
    public static function orderRefund($data){
        $refundTpl = trSystemSet::getValue("smsRefundTpl"); // 订单退款成功
        if(!empty($refundTpl["refundTpl"]) && $refundTpl["refundTplStatus"] == "1"){ // 可以发短信了
            if(!empty($data)) {
                $data["mobilePrefix"] = substr($data["mobile"], 0, -11);
                $data["mobile"] = substr($data["mobile"], -11);
                if(self::sendSms($refundTpl["refundTpl"], [
                    "：" . $data["orderSn"], "：" . $data["payMoney"]
                ], $data["mobile"], $data["mobilePrefix"])){
                    self::recordLog($refundTpl["refundTpl"], $data["mobile"], "订单成功退款");
                }
            }
        }
        return true;
    }

    // 司机接单后提醒用户
    public static function orderReceive($data, $type = "pass"){// fail
        $refundTpl = trSystemSet::getValue("remindAcceptTpl"); // 司机接单提醒用户
        if(!empty($refundTpl["remindAcceptTpl"]) && $refundTpl["remindAcceptTplStatus"] == "1"){ // 可以发短信了
            $data["mobilePrefix"] = substr($data["mobile"], 0, -11);
            $data["mobilePrefix"] = $data["mobilePrefix"] ?: "86";
            $data["mobile"] = substr($data["mobile"], -11);
            $tel = trSystemSet::getValue("customerServiceConfig");
            if (empty($tel)) {
                $tel["territoryTel"] = "";  //境内电话
                $tel["abroadTel"] = ""; //境外电话
            }
            $driverModel = new trDriver();
            $driverData = $driverModel->getFields("mobile", ["id" => $data["allotDriverId"]], true, false);
            $content = $type == "pass" ? "司机已确认接受，请准时或者提前到达上车点，司机电话：{$driverData["mobile"]}" : "司机已拒绝接单，系统会重新分配司机，请留意短信通知";
            if(self::sendSms($refundTpl["remindAcceptTpl"], [
                $data["orderSn"], $content, $tel["territoryTel"], $tel["abroadTel"]
            ], $data["mobile"], $data["mobilePrefix"])){
                self::recordLog($refundTpl["remindAcceptTpl"], $data["mobile"], "司机接单提醒用户");
                $remindSetting = trSystemSet::getValue("orderRemindSetting"); // 分配提醒设置
                if(!empty($remindSetting)){
                    $content = $type == "pass" ? "司机已确认接受，并已下发短信给用户，司机电话：{$driverData["mobile"]}" : "司机已拒绝接单，为避免耽误用户行程，请尽快重现分配，司机电话：{$driverData["mobile"]}";
                    foreach ($remindSetting as $setting){
                        if($setting["status"] == "1" && !empty($setting["value"])){ // 开启推送了
                            if(strlen($setting["value"]) > 11){
                                $mobilePrefix = substr($setting["value"], 0, -11);
                                $mobile = substr($setting["value"], -11);
                            }else{
                                $mobilePrefix = "86";
                                $mobile = $setting["value"];
                            }
                            self::sendSms($refundTpl["remindAcceptTpl"], [
                                $data["orderSn"], $content, $tel["territoryTel"], $tel["abroadTel"]
                            ], $mobile, $mobilePrefix);
                        }
                    }
                }
            }
        }
        return true;
    }

    // 订单完成提醒用户
    public static function orderFinish($data){
        $refundTpl = trSystemSet::getValue("finishTpl"); // 订单完成提醒用户
        if(!empty($refundTpl["finishTpl"]) && $refundTpl["finishTplStatus"] == "1"){ // 可以发短信了
            $data["mobilePrefix"] = substr($data["mobile"], 0, -11);
            $data["mobilePrefix"] = $data["mobilePrefix"] ?: "86";
            $data["mobile"] = substr($data["mobile"], -11);
            $tel = trSystemSet::getValue("customerServiceConfig");
            if (empty($tel)) {
                $tel["territoryTel"] = "";  //境内电话
                $tel["abroadTel"] = ""; //境外电话
            }
            if(self::sendSms($refundTpl["finishTpl"], [
                $data["orderSn"], $tel["territoryTel"], $tel["abroadTel"]
            ], $data["mobile"], $data["mobilePrefix"])){
                self::recordLog($refundTpl["finishTpl"], $data["mobile"], "订单完成提醒用户");
                $remindSetting = trSystemSet::getValue("orderRemindSetting"); // 分配提醒设置
                if(!empty($remindSetting)){
                    foreach ($remindSetting as $setting){
                        if($setting["status"] == "1" && !empty($setting["value"])){ // 开启推送了
                            if(strlen($setting["value"]) > 11){
                                $mobilePrefix = substr($setting["value"], 0, -11);
                                $mobile = substr($setting["value"], -11);
                            }else{
                                $mobilePrefix = "86";
                                $mobile = $setting["value"];
                            }
                            self::sendSms($refundTpl["finishTpl"], [
                                $data["orderSn"], $tel["territoryTel"], $tel["abroadTel"]
                            ], $mobile, $mobilePrefix);
                        }
                    }
                }
            }
        }
        return true;
    }

    // 发送验证码
    public static function sendCode($mobile, $mobilePrefix = "86"){
        $tpl = trSystemSet::getValue(SettingConf::SMS_CODE_TPL); // 订单完成提醒用户
//        if(empty($tpl["codeTpl"])) {
//            throw new \Exception("短信验证码模板未设置", 1);
//        }
        $tpl["codeTpl"] = "511202";
        if(commonModel::getCount(smsRecordTable, [
            ["mall_id", '=', request()->mallData["id"]],
            ["mobile", "=", $mobile],
            ["status", "=", 1],
            ["create_time", ">=", date("Y-m-d H:i:s", time() - 60)]
        ])){
            throw new \Exception("一分钟内请勿频繁获取验证码", 1);
        }
        $code = rand(1000, 9999);
        if(self::sendSms($tpl["codeTpl"], [$code], $mobile, $mobilePrefix, $msg)){
            SmsLogic::recordLog($tpl["codeTpl"], $mobile, SettingConf::$smsContent["codeTplContent"], $code, 1);
        }else{
            throw new \Exception($msg, 1);
        }
        return true;
    }

    // 腾讯云单发短信函数
    public static function sendSms($templateId, $data, $mobile, $prefix = "86", &$msg = '', $smsConfig = null)
    {
        if(empty($smsConfig)) {
            $smsConfig = trSystemSet::getValue("smsConfig");
        }
        if (empty($smsConfig["smsId"]) || empty($smsConfig["smsSecret"])) {
            $msg = "短信未配置";
            return false;
        }
        $random = rand(1000, 9999);
        $time = time();
        $url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=" . $smsConfig["smsId"] . "&random=" . $random;
        $sig = hash('sha256', 'appkey=' . $smsConfig["smsSecret"] . '&random=' . $random . '&time=' . $time . '&mobile=' . $mobile);
        $arr = array(
            "ext" => "",
            "extend" => "",
            "params" => $data,
            "sig" => $sig,
            "sign" => $smsConfig["smsSign"],
            "tel" => array(
                "mobile" => $mobile,
                "nationcode" => $prefix
            ),
            "time" => $time,
            "tpl_id" => $templateId,
        );
        $result = json_decode(Tools::curl($url, json_encode($arr, true)), true);
        if ($result["result"] != '0') {
            Tools::writeLog("发送短信失败：".var_export($result,true) . "--" . var_export($arr,true), "sms.txt");
            $msg = $result["errmsg"];
            return false;
        } else {
            return true;
        }
    }

    // 记录短信
    public static function recordLog($templateId, $mobile, $message, $code = NULL, $status = 2){
        commonModel::toAdd(smsRecordTable, [
            "mall_id" => request()->mallData["id"], "mobile" => $mobile, "tpl" => $templateId, "content" => $message, "code" => $code, "status" => $status,
            "ip" => Tools::get_client_ip(), "create_time" => date("Y-m-d H:i:s")
        ]);
    }

    //检查短信验证码
    public static function checkValidateCode($code, $mobile, &$msg = ""){
        $smsLog = commonModel::getList(smsRecordTable, "code,id", [
            "mall_id" => request()->mallData["id"], "mobile" => $mobile, "status" => 1
        ], 1, 1, "create_time desc", false);
        if(empty($smsLog)){
            $msg = "请获取验证码";
            return false;
        }
        if(trim($code) != $smsLog[0]["code"]){
            $msg = "验证码不正确";
            return false;
        }
        commonModel::toUpdate(smsRecordTable, ["status" => 2], ["id" => $smsLog[0]["id"]]); // 改成已使用
        return true;
    }
}